import * as types from '../mutations-types'

export default {
  state: {
    added: [],
    // 此处直接用data存放count，并在添加、减少物品时操作此data,如此可提高获取count的效率
    // 但是，很容易忘记进行相关处理时(添减，清空)忘记处理count,所以还是通过gettter计算更好
    addedCount: 0
  },
  getters: {
    productsInCart: state => state.added,
    productsCountInCart: state => state.addedCount
  },
  actions: {
    checkOut ({ commit }) {
      commit(types.CART_CHECKOUT)
    }
  },
  mutations: {
    [types.ADD_TO_CART] (state, { id }) {
      const record = state.added.find(p => p.id === id)
      if (!record) {
        state.added.push({
          id,
          quantity: 1
        })
      } else {
        record.quantity++
      }
      state.addedCount++
    },
    [types.REMOVE_FROM_CART] (state, { id }) {
      const record = state.added.find(p => p.id === id)
      if (record && record.quantity >= 1) {
        record.quantity--
        state.addedCount--
      }
    },
    [types.CART_CHECKOUT] (state) {
      state.added.splice(0)
      state.addedCount = 0
    }
  }
}
